<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>1_引出生命周期</title>
    <!-- 引入 react核心库 -->
    <script type="text/javascript" src="../js/react.development.js"></script>
    <!-- 引入 react-dom 用于支持操作DOM -->
    <script type="text/javascript" src="../js/react-dom.development.js"></script>
    <!-- 引入 babel 用于将 jsx转为 js -->
    <script type="text/javascript" src="../js/babel.min.js"></script>
</head>
<body>
<div id="test"></div>
<script type="text/babel">

    class Demo extends React.Component {
        // 初始化状态 透明度 opacity=1
        state = {opacity: 1}

        death = ()=> {
            ReactDOM.unmountComponentAtNode(document.getElementById("test"));
        }

        /**
         * 组件挂载完毕生命周期钩子
         */
        componentDidMount() {
            this.timer = setInterval(()=> {
                let {opacity} = this.state;
                opacity -= 0.1;
                if (opacity <= 0) {
                    opacity = 1;
                }
                this.setState({opacity: opacity})
            }, 200);
        }

        /**
         * 组件将要卸载
         */
        componentWillUnmount() {
            console.log("@");
            clearInterval(this.timer);
        }

        render() {
            console.log("render");
            return(
                <div>
                    <h2 style={{opacity:this.state.opacity}}>React 学不会怎么办？</h2>
                    <button onClick={this.death}>不活了..</button>
                </div>
            )
        }
    }

    ReactDOM.render(<Demo />, document.getElementById("test"));

</script>
</body>
</html>